"""
数据库迁移脚本 - 添加手机、医院和职位字段
"""
import sqlite3
import os

def migrate_database():
    """迁移数据库，添加新字段"""
    db_path = "users.db"
    
    if not os.path.exists(db_path):
        print("数据库文件不存在，跳过迁移")
        return
    
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    try:
        # 检查是否已经存在新字段
        cursor.execute("PRAGMA table_info(users)")
        columns = [column[1] for column in cursor.fetchall()]
        
        # 添加缺失的字段
        if 'phone' not in columns:
            cursor.execute("ALTER TABLE users ADD COLUMN phone TEXT")
            print("添加 phone 字段")
        
        if 'hospital' not in columns:
            cursor.execute("ALTER TABLE users ADD COLUMN hospital TEXT")
            print("添加 hospital 字段")
        
        if 'position' not in columns:
            cursor.execute("ALTER TABLE users ADD COLUMN position TEXT")
            print("添加 position 字段")
        
        # 对于现有用户，设置默认值
        cursor.execute("""
            UPDATE users 
            SET phone = '未设置', hospital = '未设置', position = '医学生' 
            WHERE phone IS NULL OR hospital IS NULL OR position IS NULL
        """)
        
        conn.commit()
        print("数据库迁移完成")
        
    except Exception as e:
        print(f"数据库迁移失败: {e}")
        conn.rollback()
    finally:
        conn.close()

if __name__ == "__main__":
    migrate_database() 